﻿using RgUtility.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WechatModule.Tool;
using WechatModule.Model;

namespace WechatModule.API
{
    /// <summary>
    /// OAuthAPI
    /// </summary>
    public class WechatOAuthAPI
    {
        static System.Web.Script.Serialization.JavaScriptSerializer jSer = new System.Web.Script.Serialization.JavaScriptSerializer();
        /// <summary>
        /// 获得Token
        /// </summary>
        /// <param name="Code"></param>
        /// <returns></returns>

        public static BizResult<OAuthAccessToken, Error> GetOAuthToken(string Code)
        {
            BizResult<OAuthAccessToken, Error> br = new BizResult<OAuthAccessToken, Error>();
            string jsStr = ReuqestTool.GetWechatJson("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WechatGlobalVar.AppId + "&secret=" + WechatGlobalVar.AppSecret + "&code=" + Code + "&grant_type=authorization_code");

            if ((jsStr + "").Contains("errcode"))
            {

                br.ResultState = BizState.Warning;
                var error = jSer.Deserialize<Error>(jsStr);
                if (error != null)
                {
                    br.AddMessage(error.errmsg);
                    br.Data1 = error;
                }
                else
                {
                    br.AddMessage(jsStr + "");
                }
                return br;
            }
            OAuthAccessToken Oauth_Token_Model = jSer.Deserialize<OAuthAccessToken>(jsStr);
            br.Data = Oauth_Token_Model;

            return br;
        }
        /// <summary>
        /// 刷新token
        /// </summary>
        /// <param name="REFRESH_TOKEN"></param>
        /// <returns></returns>
        public static OAuthAccessToken RefreshOAuthToken(string REFRESH_TOKEN)
        {
            string json = ReuqestTool.GetWechatJson("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + WechatGlobalVar.AppId + "&grant_type=refresh_token&refresh_token=" + REFRESH_TOKEN);
            OAuthAccessToken Oauth_Token_Model = jSer.Deserialize<OAuthAccessToken>(json);
            return Oauth_Token_Model;
        }
        /// <summary>
        /// 获得OAuth2.0用户信息
        /// </summary>
        /// <param name="REFRESH_TOKEN"></param>
        /// <param name="OPENID"></param>
        /// <returns></returns>
        protected UserInfo GetOAuthUserInfo(string REFRESH_TOKEN, string OPENID)
        {
            string json = ReuqestTool.GetWechatJson("https://api.weixin.qq.com/sns/userinfo?access_token=" + REFRESH_TOKEN + "&openid=" + OPENID);
            UserInfo OAuthUser_Model = jSer.Deserialize<UserInfo>(json);
            return OAuthUser_Model;
        }
    }
}